package com.podium.auth.filter;

import com.podium.auth.entity.LoginUser;
import com.podium.auth.service.TokenService;
import com.podium.auth.utils.ServletUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author 邵文泽
 * @description JWT认证过滤器
 * @date 2025-04-14 10:52
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,@NonNull HttpServletResponse response,@NonNull FilterChain filterChain) throws ServletException, IOException {
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        loginUser,
                        null,
                        loginUser.getAuthorities()
                );
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                logger.info("用户身份验证成功: {}, 请求路径: {}, 来源IP: {}", loginUser.getUsername(), ServletUtils.getRequestPath(), ServletUtils.getClientIp());
            }
        } catch (Exception e) {
            logger.error("用户身份验证失败，请求路径: {}, 来源IP: {}",  ServletUtils.getRequestPath(), ServletUtils.getClientIp(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }finally {
            filterChain.doFilter(request, response);
        }
    }
}
